package com.chixing.mqConsumer;

import com.chixing.config.RabbitMQConfig;
import com.chixing.entity.DTO.MessageDTO;
import com.chixing.mapper.OrderCancelRulesMapper;
import com.chixing.mapper.UserMessageMapper;
import com.chixing.utils.WebSocketProcess;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 订单预定成功的消费者
 */
@Component
public class OrderSuccessConsumer {
    @Autowired
    private WebSocketProcess webSocketProcess;
    @Autowired
    private UserMessageMapper userMessageMapper;


    @RabbitListener(queues = {RabbitMQConfig.ORDER_SUCCESS_QUEUE, RabbitMQConfig.ORDER_PAYMENT_QUEUE,RabbitMQConfig.ORDER_DELAY_PAYMENT_QUEUE})
    public void pushMessageToUser(MessageDTO messageDTO, Message message, Channel channel){

        Long userId = messageDTO.getUserId();
        Long id = messageDTO.getId();
        System.out.println("消费者收到MQ中的消息，准备推送给用户:"+userId);
        boolean delivered = false;
        try {
            //通过websocket推送消息
            delivered = webSocketProcess.sendMessage(userId,messageDTO);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 根据推送结果更新状态
        if (delivered) {
            // WebSocket 成功发送
            userMessageMapper.updateDeliveredStatus(id, LocalDateTime.now());
            System.out.println("消息已送达，状态更新为 DELIVERED");
        } else {
            // 用户离线，消息已存 Redis，状态保持 UNREAD
            System.out.println("用户离线，消息存 Redis，状态保持 UNREAD");
        }
        try {
            //手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
